﻿/**
 * 查询客户
 */
function findClient(eNum){
	var n = $("#"+eNum).val();
	$.pdialog.open("findClient.action?clinentCustomers.customersName="+n+"&&eNum="+eNum, "findClient", "查询客户",{"width":"800","height":"400"});
}

/**
 * 将值带回页面
 */
function returnValue(){
	var id = $("#Num").val();
	var v = $("input[name='orderCustomerNumber']:checked").val();
	$("#"+id).val(v);
	if(id == 'inpcustomerName' || id == 'outcustomerName'){
		var num = $("input[name='orderCustomerNumber']:checked").parent().parent().parent().children().eq(1).text();
		$("#" + id + "Hidd").val(num);
	}
	$.pdialog.closeCurrent();
}

/**
 * 查询客户信息并计算余额
 */
function calcBalance(){
	$.pdialog.open("orderManager/calcBalanceAndCustomerInfo.jsp", "calcBalance", "查询客户",{"width":"800","height":"400"}); 
}

//****************************************新建收货单与出货单***********************************************//
/**
 * 新建收货单或者出货单"上一步"按钮
 */
function backOper(type){
		document.getElementById(type + "subBut").style.display = "none";
		document.getElementById(type + "backBut").style.display = "none";
		document.getElementById(type + "nextBut").style.display = "block";
		$("#" + type + "orders").fadeOut("slow");
		$("div[name='" + type + "hiddenDiv']").fadeIn("slow");
		nextOper
	}

/**
 * 新建收货单或者出货单"下一步"按钮
 * type 区别是出货单还是收货单
 */
function nextOper(type){
		if($("#"+type+"depotMode").val()==""){
			alertMsg.error("请选择一种物流模式！");
				return;
		}
		if(type == 'inp'){
			if($("#inpcustomerName").val() == ""){
				alertMsg.error("请选择一个客户！");
				return;
			}
		}
		if(type == 'out'){
			if($("#outchannelNum").val() == ""){
				alertMsg.error("请选择一个渠道！");
				return;
			}
		}
		document.getElementById(type + "subBut").style.display = "block";
		document.getElementById(type + "backBut").style.display = "block";
		document.getElementById(type + "nextBut").style.display = "none";
		$("#" + type + "orders").fadeIn("slow");
		$("div[name='" + type + "hiddenDiv']").fadeOut("slow");
		
		//动态追加元素
		var a = document.getElementById(type + "orderBody");
		$("tr[name='"+type+"rowName']").remove();
		if(type == "inp"){			//如果类型是收货单的
			$.post("findOrdersForAddDepot.action", {
				"clientOrderBean.customerBean.orderCustomerNumber":$("#" + type + "customerNameHidd").val(),
				"clientOrderBean.orderClass" : $("#" + type + "depotMode").val(),
				"clientOrderBean.orderTransport" : $("#" + type + "channelNum").val()
			}, function(data){
				$(data).each(function(i){
					if(i == 0){
						var fTR= $("#inpFirstTR").children();
						fTR.eq(0).html("<input type='checkbox' name='"+type+"orderNum' value='"+this.clinentOrderId+"'>");
						fTR.eq(1).html((i+1));
						fTR.eq(2).html(this.clinentOrderId);
						fTR.eq(3).html(this.orderReference);
						fTR.eq(4).html(this.clientCompany.companyCode);
						fTR.eq(5).html(this.customerBean.customersName);
						fTR.eq(6).html(this.orderTransport);
						fTR.eq(7).html(this.orderDestination);
						fTR.eq(8).html(this.orderSettlementwrite);
						fTR.eq(9).html(this.orderAmount);
						fTR.eq(10).html('已预报');
						fTR.eq(11).html(this.orderDatetime.substring(0,10));
					} else {
						var or = "<tr name='"+type+"rowName'>" +
								"<td><input type='checkbox' name='"+type+"orderNum' value='"+this.clinentOrderId+"'></td>" +
								"<td>"+(i+1)+"</td>" +
								"<td>"+this.clinentOrderId+"</td>" +
								"<td>"+this.orderReference+"</td>" +
								"<td>"+this.clientCompany.companyCode+"</td>" +
								"<td>"+this.customerBean.customersName+"</td>" +
								"<td>"+this.orderTransport+"</td>" +
								"<td>"+this.orderDestination+"</td>" +
								"<td name='"+type+"weight' >"+this.orderSettlementwrite+"</td>" +
								"<td name='"+type+"amount' >"+this.orderAmount+"</td>" +
								"<td>已预报</td>" +
								"<td>"+this.orderDatetime.substring(0,10)+"</td>" +
							 "</tr>";
					$("#inporderBody").append(or);			//向表格追加一行
			}
			});
		});
	} else {
			//获取所有客户
			var allCustomer = "";
			$.post("findDepotOrdersForAddOutDepot.action",{
				"depotOrder.orderCustomerNumber":$("#" + type + "customerNum").val(),
				"depotOrder.orderCode":$("#" + type + "depotMode").val(),
				"depotOrder.orderTransport":$("#" + type + "channelNum").val()
			},function(data){
				$(data).each(function(i){
					if(i == 0){
						var fTR= $("#outFirstTR").children();
						fTR.eq(0).html("<input type='checkbox' name='"+type+"orderNum' value='"+this.clientOrderId+"'>");
						fTR.eq(1).html((i+1));
						fTR.eq(2).html(this.clientOrderId);
						fTR.eq(3).html(this.customersName);
						fTR.eq(4).html(this.orderTransport);
						fTR.eq(5).html(this.orderSettlementWeight);
						fTR.eq(6).html(this.orderAmount);
						fTR.eq(7).html(this.orderAdditional);
						fTR.eq(8).html($("#outchannelNum").find("option:selected").text());
						fTR.eq(9).html(this.orderSettlementWeight);
						fTR.eq(10).html(this.orderDepotAmount.toFixed(2));
						fTR.eq(11).html(this.orderDepotAdditional);
						fTR.eq(12).html(((this.orderDepotAmount+this.orderDepotAdditional)-(this.orderAmount+this.orderAdditional)).toFixed(2));
						fTR.eq(13).html(this.orderDepotAddDate.substring);
						allCustomer += this.orderCustomerNumber;
					} else {
						var newTR = "<tr name='"+type+"rowName'>" +
								"<td><input type='checkbox' name='"+type+"orderNum' value='"+this.clientOrderId+"'></td>" +
							  	"<td class='center'>"+(i+1)+"</td>" +
							  	"<td class='center'>"+this.clientOrderId+"</td>" +
							  	"<td class='center'>"+this.customersName+"</td>" +
							  	"<td class='center'>"+this.orderTransport+"</td>" +
							  	"<td class='center'>"+this.orderSettlementWeight+"</td>" +
							  	"<td class='center'>"+this.orderAmount+"</td>" +
							  	"<td class='center'>"+this.orderAdditional+"</td>" +
							  	"<td class='center' style='color:red'>"+$("#outchannelNum").find("option:selected").text()+"</td>" +
							  	"<td class='center' style='color:red' name='"+type+"weight'>"+this.orderSettlementWeight+"</td>" +
							  	"<td class='center' style='color:red' name='"+type+"amount'>"+this.orderDepotAmount.toFixed(2)+"</td>" +
							  	"<td class='center' style='color:red'>"+this.orderDepotAdditional+"</td>" +
							  	"<td class='center' style='color:blue'>"+((this.orderDepotAmount+this.orderDepotAdditional)-(this.orderAmount+this.orderAdditional)).toFixed(2)+"</td>" +
							  	"<td class='center'>"+this.orderDepotAddDate.substring(0,10)+"</td>" +
							  "</tr>";
						$("#outorderBody").append(newTR);
						allCustomer += ","+this.orderCustomerNumber;
					}
				});
				$.post("showType.action",{
					"ids":allCustomer
				},function(data){
					$(data).each(function(){
						var balance = this.balance;		//取出当前客户余额
						var trList = $("tr:contains('"+this.customersName+"')");	//取出当前客户所属订单
						var sumamount = 0;
						//如果余额小于0，该客户的货全部暂扣
						if(balance< 0){
							$(trList).each(function(){
								$(this).children().eq(0).html("<font color='red'>暂扣</font>");
							});
						}
					});
				});
			});
	}
}

/**
 * 新建收货单或出货单点击“提交”触发的函数
 * @param {Object} ckName
 */
function getCheckBoxVal(ckName,type){
	var ids = "";				//选中的订单号
	var cks = $("input[name='"+ ckName +"']:checked");  //获取选中的复选框对象
	var trs = cks.parent().parent();					//获取选中订单的所属行的集合
	var totalWeight = 0;		//总重量
	var totalAmount = 0;		//总金额
	$(trs).each(function(){
		totalWeight += Number($(this).children("[name="+type+"weight]").text());		//获取每条订单的重量
		totalAmount += Number($(this).children("[name="+type+"amount]").text());		//获取每条订单的金额
	});
	if(cks.length == 0){
		alertMsg.error("至少选择一条订单！");
		return false;
	} else if (cks.length != $("#"+type+"pieces").val()){
		alertMsg.error("件数与选中订单数量不同，请确认后再提交！");
		return false;
	} else if (cks.length != $("#"+type+"votes").val()){
		alertMsg.error("票数与选中订单数量不同，请确认后再提交！");
		return false;
	} else if (totalWeight.toFixed(3) > $("#"+type+"totalWeight").val()){
		alertMsg.confirm("实际重量小于所选订单总重量，是否让系统自动调整？",{
			okCall:function(){
				$("#"+type+"totalWeight").attr("value",totalWeight.toFixed(3));
			}
		});
		return false;
	} else if (totalAmount > $("#"+type+"totalAmount").val()){
		alertMsg.confirm("计算金额小于所选订单总金额，是否让系统自动调整？",{
			okCall:function(){
				$("#"+type+"totalAmount").attr("value",totalAmount.toFixed(2));
			}
		});
		return false;
	}
	//拼接字符串
	$(cks).each(function(i){
		if(cks.length == i+1){
			ids += "'"+$(this).val() + "'";
		} else {
			ids += "'"+$(this).val() + "',";
		}
	});
	
	$("#"+type+"depotNums").attr("value",ids);
	return true;
}


//****************************************财务管理：审核收货单和出货单******************************************//
/**
 * 审核收货单或出货单的重量和金额
 * @param {Object} type 区别是收货单或者出货单
 */
function exWeightAndAmount(type){
	var tWeight,tAmount,tAdditional;		//用来存放获取的重量、金额和附加费用的对象
	var totalWeight = 0;		//总重量
	var totalAmount = 0;		//总金额
	var totalAdditional = 0;	//总附件费用
	
	if(type == 'out'){ //如果是出货
		tWeight = $("#"+type+"Ex input[name='"+type+"DepotNums']:checked").parent().parent().parent()
					.find("."+type+"Weight");		//获取选中的记录的收货重量列的所有对象
		tAmount = $("#"+type+"Ex input[name='"+type+"DepotNums']:checked").parent().parent().parent()
					.find("."+type+"Amount");		//获取选中的记录的收货金额列的所有对象
		tAdditional = $("#"+type+"Ex input[name='"+type+"DepotNums']:checked").parent().parent().parent()
					.find("."+type+"Additional");	//获取选中的记录的收货附加费用列的所有对象
	} else {		   //否则是收货
		tWeight = $("#"+type+"Ex ."+type+"Weight");			//获取收货重量列的所有对象
		tAmount = $("#"+type+"Ex ."+type+"Amount");			//获取收货金额列的所有对象
		tAdditional = "#"+type+"Ex ."+type+"Additional";	//获取收货附加费用列的所有对象
	}
	//计算总重量
	$(tWeight).each(function(){
		totalWeight += Number($(this).val());	//$(this).val()是用JQuery对象访问
	});
	//计算总金额
	$(tAmount).each(function(){
		totalAmount += Number($(this).val());
	});
	//计算总附加费用
	$(tAdditional).each(function(){
		totalAdditional += Number(this.value);	//this.value使用DOM对象访问
	});
	if($("#"+type+"TotalWeight").val() - totalWeight > 0.02 || 
	   $("#"+type+"TotalWeight").val() - totalWeight < -0.02){
		
		alertMsg.error("结算重量与收货总重量不相等，请调整后再提交!");
		return false;
	}
	if($("#"+type+"TotalAmount").val() - (totalAmount + totalAdditional) > 0.02 || 
	   $("#"+type+"TotalAmount").val() - (totalAmount + totalAdditional) < -0.02){
			alertMsg.error("结算金额与收货总金额不相等，请调整后再提交!");
			return false;
	}
	return true;
}


/**
 * 自动调整重量和金额，并且把差价平摊到每一条记录上（审核收货单）
 * @param {Object} type 区别是收货单或者出货单
 */
function autoAdjust(type){
	if($("#"+type+"TotalWeight").val() == 0){
		alertMsg.error("计算重量不能为空或0");
		return;
	}
	if($("#"+type+"TotalAmount").val() == 0){
		alertMsg.error("计算金额不能为空或0");
		return;
	}
	var tWeight,tAmount,tAdditional = "";		//用来存放获取的重量、金额和附加费用的对象
	
	//平摊重量
	do{
		var totalWeight = 0;		//总重量
		if(type == 'out'){
			//判断是都至少选中了一条订单
			if($("#"+type+"Ex input[name='"+type+"DepotNums']:checked").length == 0){
				alertMsg.error("请至少选择一条要调整的订单！");
				return false;
			}
			tWeight = $("#"+type+"Ex input[name='"+type+"DepotNums']:checked").parent().parent().parent()
					.find("."+type+"Weight");				//获取选中的记录的收货重量列的所有对象
		} else {
			tWeight = $("#"+type+"Ex ."+type+"Weight");		//获取收货重量列的所有对象
		}
		
		//计算总重量
		$(tWeight).each(function(){
			totalWeight += parseFloat($(this).val());	//$(this).val()是用JQuery对象访问
		});
		totalWeight = totalWeight.toFixed(3);
		//算出总重量与实际总重量的差值
		var diffWeight = ($("#"+type+"TotalWeight").val() - totalWeight).toFixed(5);
//		alert(diffWeight);
		//计算结果保留五位小数，四舍五入
		var avgWeight = (diffWeight/tWeight.length).toFixed(5);				
		//本身的值加上平均差值,保留三位小数
		$(tWeight).each(function(){
			$(this).val((parseFloat($(this).val()) + parseFloat(avgWeight)).toFixed(3));
		});
//	alert(totalWeight);
	}while(diffWeight > 0.005 || diffWeight < -0.005);
	
	//平摊金额
	do{
		var totalAmount = 0;		//总金额
		var totalAdditional = 0;	//总附件费用
		if(type == 'out'){
			tAmount = $("#"+type+"Ex input[name='"+type+"DepotNums']:checked").parent().parent().parent()
					.find("."+type+"Amount");		//获取选中的记录的收货金额列的所有对象
			tAdditional = $("#"+type+"Ex input[name='"+type+"DepotNums']:checked").parent().parent().parent()
					.find("."+type+"Additional");	//获取选中的记录的收货附加费用列的所有对象
		} else {
			tAmount = $("#"+type+"Ex ."+type+"Amount");			//获取收货金额列的所有对象
			tAdditional = "#"+type+"Ex ."+type+"Additional";	//获取收货附加费用列的所有对象
		}
		
		//计算总金额
		$(tAmount).each(function(){
			totalAmount += parseFloat($(this).val());
		});
		totalAmount = totalAmount.toFixed(2);
		//计算总附加费用
		$(tAdditional).each(function(){
			totalAdditional += parseFloat(this.value);	//this.value使用DOM对象访问
		});
		var diffAmount = ($("#"+type+"TotalAmount").val() - (totalAmount + totalAdditional));	//算出差价
		var avgAmount = (diffAmount/tAmount.length).toFixed(5);		//计算结果保留两位小数，四舍五入
		//本身的值加上平均差值,保留两位小数
		$(tAmount).each(function(){
			$(this).val((parseFloat($(this).val())+ parseFloat(avgAmount)).toFixed(3));
		});
	}while(diffAmount > 0.02 || diffAmount < -0.02);
//	alert(totalAmount);
}

/**
 * 审核出货单时单击复选框出发的事件
 */
function checkBoxClick(element){
	var elem = $(element).parent().parent().parent()
	.find(".outWeight,.outAmount,.outAdditional").attr("readOnly",!element.checked);
	if(element.checked){
		elem.removeClass("readonly");
	} else {
		elem.addClass("readonly");
		var hiddElem = $(element).parent().parent().parent().find(".outWeightHidd,.outAmountHidd,.outAdditionalHidd");
		$(elem).each(function(i){
			$(this).val(hiddElem[i].value);
		});
	}
}

/**
 * 显示复选框或者是“暂扣”，
 */
function ctest(){
	$.post("calcBalance.action",{
		"type":"addOutDepot",
		"prepaidOrder.orderCustomerNumber":"MC0000000066"
	},function(data){
		alert(data.balance);
	});
}